#include "head.h"

// 实现文件上传功能
int putsFunc(int sockfd, const char *filename) {
    // train_t train;
    // bzero(&train, sizeof(train));
    // int fd = open(filename, O_RDWR);

    // struct stat statbuf;
    // fstat(fd,&statbuf);
    // printf("filesize = %ld\n", statbuf.st_size);
    // train.length = sizeof(statbuf.st_size);
    // memcpy(train.data,&statbuf.st_size,train.length);
    // send(sockfd,&train,sizeof(train.length)+train.length,MSG_NOSIGNAL);
    // sendfile(sockfd,fd,NULL,statbuf.st_size);

    // 先接收报错
    int ifError;
    recvn(sockfd, &ifError, sizeof(int));
    if (ifError != 0) {
        // 接收一个小火车
        print_network_message(sockfd);
        return -1;
    }

    printf("upload begin\n");
    train_t train_file;
    bzero(&train_file, sizeof(train_file));

    //char MD5[128] = {0};
    //getFileMD5(filename, MD5);
    //strcpy(train_file.data, MD5);
    //train_file.length = strlen(MD5);
    //send(sockfd, &train_file, sizeof(int)+train_file.length, MSG_NOSIGNAL);

    //recvn(sockfd, &ifError, sizeof(int));
    //if(ifError == 888){
    //    bzero(&train_file, sizeof(train_t));
    //    recvn(sockfd, &train_file.length, sizeof(int));
    //    recvn(sockfd, train_file.data, train_file.length);
    //    puts(train_file.data);
    //    return -1;
    //}

    //int ret;
    //recvn(sockfd, &ret, sizeof(int));
    //if(ret == 999){
    //    printf("秒传成功\n");
    //    return 0;
    //}

    // 打印上传开始信息
    int fd = open(filename, O_RDWR);// 只读的方式打开文件
    struct stat statbuf;
    fstat(fd, &statbuf); // 使用 fstat 获取文件的状态信息
    // train_file.length=sizeof(statbuf.st_size);
    // memcpy(train_file.data, &statbuf.st_size, train_file.length);
    // send(sockfd, &train_file, sizeof(train_file.length)+train_file.length, MSG_NOSIGNAL);
    // bzero(&train_file, sizeof(train_file));
    
    // 循环读取并发送文件内容
    while(1){
        bzero(&train_file, sizeof(train_file)); 
        // 使用read函数从磁盘中读取文件数据
        ssize_t sret=read(fd,train_file.data,sizeof(train_file.data));
        if(sret==0){ // 此时表示文件已经读取完毕
            printf("upload over\n");
            break;
        }
        // 将读取完的文件数据发送给客户端
        // MSG_NOSIGNAL 标志用于防止发送过程中产生信息
        train_file.length = sret;
        sret = send(sockfd,&train_file,sizeof(train_file.length)+train_file.length,MSG_NOSIGNAL);
    }

    // 发送结束标志，
    train_file.length=0;
    send(sockfd,&train_file,sizeof(train_file.length),MSG_NOSIGNAL);
    // 报错信息呢
    //
    //
    //
    //
    // 写前面
    close(fd);
    return 0;
}
